// pages/material/pages/basis/form_a/index.js
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        id:0,
        picker_a: [ //类型
            {
                id: 1,
                name: '房产公证'
            },
            {
                id: 2,
                name: '股权公证'
            },
            {
                id: 3,
                name: '公证类型a'
            },
            {
                id: 4,
                name: '公证类型b'
            }
        ],
        update_disabled:false,
        number_goods: 0,
        pick_a: '点击选择',
        matter_id:0,
        //委托人资料 （可多人）
        client_list: [],
        image_src: {},
        no_list: true, //是否有委托人数据
        //下面是父母的资料
        marriage: '', //婚姻状态
        marriage_license: '', //结婚证
        marriage_files: [], //结婚证多图
        marriage_max: 9, //最多上传张数
        marriage_max_vir: 9, //最多上传张数
        
        divorce: '', //离婚证
        divorce_files: [], //离婚协议
        divorce_max: 9, //最多上传张数
        divorce_max_vir: 9, //最多上传张数

        deed: '', //房产证
        deed_files: [], //房产证多图
        deed_max: 9, //最多上传张数
        deed_max_vir: 9, //最多上传张数


        buy_files: [], //购房协议
        buy_max: 9, //最多上传张数
        buy_max_vir: 9, //最多上传张数 

        inquire_files: [], //房产信息查询（产调）
        inquire_max: 9, //最多上传张数
        inquire_max_vir: 9, //最多上传张数 
        //受托人资料 （可多人）
        trustee_list: [],
        trustee_no: true,
        other_files: [], //其他
        other_max: 9, //最多上传张数
        other_max_vir: 9, //最多上传张数

        amount: 500, //总金额
    },
        
    //类型选择
    picker_a: function (e) {
        this.setData({
            pick_a: e.detail.value,
            matter_id:this.data.picker_a[e.detail.value].id,
        })
    },
    //添加委托人
    to_add: function (e) {
        if(!this.data.update_disabled){
            wx.navigateTo({
                url: '/pages/material/pages/basis/client_a/index',
            })
        }
        
    },
    //修改委托人
    to_revise: function (e) {
        const index = e.currentTarget.dataset.index;
        wx.navigateTo({
            url: '/pages/material/pages/basis/client_a/index?index=' + index,
        })
    },
    //删除委托人
    delete_client: function (e) {
        var that = this;
        const id = e.currentTarget.dataset.id;
        const on_index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '删除提醒',
            content: '确认删除此委托人吗？',
            confirmText: '确认',
            confirmColor: '#1ac3cb',
            success(res) {
                if (res.confirm) { //确认删除
                    let lists = that.data.client_list;
                    setTimeout(() => {
                        lists.splice(on_index, 1);
                        if (lists.length == 0) {
                            that.setData({
                                no_list: true
                            })
                        }
                        that.setData({
                            client_list: lists,
                        })
                        wx.showToast({
                            title: '删除成功',
                            icon: 'success',
                            mask: true,
                            duration: 1500
                        })
                    }, 500)
                } else if (res.cancel) { //取消
                    wx.showToast({
                        title: '已取消删除',
                        icon: 'none',
                        mask: true,
                        duration: 1500
                    })
                }
            }
        })
    },

    //添加受托人
    add_trustee: function (e) {
        wx.navigateTo({
            url: '/pages/material/pages/basis/trustee_a/index',
        })
    },
    //修改受托人
    to_trustee: function (e) {
        const index = e.currentTarget.dataset.index;
        wx.navigateTo({
            url: '/pages/material/pages/basis/trustee_a/index?index=' + index,
        })
    },
    //删除受托人
    delete_trustee: function (e) {
        var that = this;
        const id = e.currentTarget.dataset.id;
        const on_index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '删除提醒',
            content: '确认删除此受托人？',
            confirmText: '确认',
            confirmColor: '#1ac3cb',
            success(res) {
                if (res.confirm) { //确认删除
                    let lists = that.data.trustee_list;
                    setTimeout(() => {
                        lists.splice(on_index, 1);
                        if (lists.length == 0) {
                            that.setData({
                                trustee_no: true
                            })
                        }
                        that.setData({
                            trustee_list: lists,
                        })

                        wx.showToast({
                            title: '删除成功',
                            icon: 'success',
                            mask: true,
                            duration: 1500
                        })
                    }, 500)
                } else if (res.cancel) { //取消
                    wx.showToast({
                        title: '已取消删除',
                        icon: 'none',
                        mask: true,
                        duration: 1500
                    })
                }
            }
        })
    },
    set_input: function (e) {},
    //图片选择
    choose_images: function (e) {
        var that = this;
        let source = e.currentTarget.dataset.source; //当前占位图名字
        let type = e.currentTarget.dataset.type; // 类型（单图/多图）
        if (type == 0) { //单图
            wx.chooseImage({
                count: 1,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths
                    var upload_img = source
                    that.setData({
                        [upload_img]: src
                    });
                    var tempFilePaths = res.tempFilePaths
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        wx.uploadFile({
                            url: 'https://gz.gzrzvisa.com/data/api.upload/add',
                            filePath: tempFilePaths[i],
                            name: "file",
                            header: {
                                "content-type": "multipart/form-data"
                            },
                            success: function (res) {
                                
                                if (res.statusCode == 200) {
                                    wx.showToast({
                                        title: "上传成功",
                                        icon: "none",
                                        duration: 1500
                                    })
                        
                                    that.data.image_src[upload_img] = res.data
                                    console.log(that.data.image_src[upload_img]);
                                }
                            },
                            fail: function (err) {
                                wx.showToast({
                                title: "上传失败",
                                icon: "none",
                                duration: 2000
                                })
                            },
                            complete: function (result) {
                                console.log(result.errMsg)
                            }
                        })
                    }
                }
            });
        } else if (type == 1) { //多图
            var in_source = source + '_files'; //当前占位图名字
            let in_count = source + '_max_vir'; //当前占位图名字
            let num_vir = e.currentTarget.dataset.num_vir; //限制数值
            wx.chooseImage({
                count: num_vir,
                sizeType: ['original', 'compressed'],
                sourceType: ['album', 'camera'],
                success: res => {
                    const src = res.tempFilePaths;
                    console.log(src)
                    that.setData({
                        [in_count]: num_vir + 1,
                        [in_source]: that.data[in_source].concat(src)
                    });
                    var tempFilePaths = res.tempFilePaths
                    for (var i = 0; i < tempFilePaths.length; i++) {
                        wx.uploadFile({
                            url: 'https://gz.gzrzvisa.com/data/api.upload/add',
                            filePath: tempFilePaths[i],
                            name: "file",
                            header: {
                                "content-type": "multipart/form-data"
                            },
                            success: function (res) {
                                if (res.statusCode == 200) {
                                    wx.showToast({
                                        title: "上传成功",
                                        icon: "none",
                                        duration: 1500
                                    })
                        
                                    if(typeof(that.data.image_src[in_source]) == 'undefined'){
                                        that.data.image_src[in_source] = [];
                                    }
                                    that.data.image_src[in_source] = that.data.image_src[in_source].concat(res.data)
                                    console.log(that.data.image_src[in_source]);
                                }
                            },
                            fail: function (err) {
                                wx.showToast({
                                title: "上传失败",
                                icon: "none",
                                duration: 2000
                                })
                            },
                            complete: function (result) {
                                console.log(result.errMsg)
                            }
                        })
                    }
                }
            });
        }
    },
    //删除图片
    to_delete: function (e) {
        var that = this;
        var select_type = e.currentTarget.dataset.source; //当前占位图名字
        that.setData({
            [select_type]: '',
        });
        that.data.image_src[select_type] = '';
    },
    //查看图片
    previewImage: function (e) {
        var source = e.currentTarget.dataset.source;
        wx.previewImage({
            current: e.currentTarget.source, // 当前显示图片的http链接
            urls: source // 需要预览的图片http链接列表
        })
    },
    //多图查看图片
    preview_image: function (e) {
        var that = this
        let files = e.currentTarget.dataset.source
        var img = e.currentTarget.dataset.img
        wx.previewImage({
            current: img, // 当前显示图片的http链接
            urls: that.data[files] // 需要预览的图片http链接列表
        })
    },
    //删除图片
    // to_delete: function (e) {
    //     var that = this;
    //     var index = e.currentTarget.dataset.index;
    //     var images = that.data.files;
    //     images.splice(index, 1);
    //     that.setData({
    //         photo_count: that.data.photo_count + 1,
    //         files: images,
    //     });
    // },
    //多图删除
    delete_set: function (e) {
        console.log(e)
        var that = this;
        let source = e.currentTarget.dataset.source;
        var in_source = source + '_files'; //当前占位图名字
        let in_count = source + '_max_vir'; //当前占位图名字
        let num_vir = e.currentTarget.dataset.num_vir; //限制数值
        let index = e.currentTarget.dataset.index;
        let images = that.data[in_source];
        images.splice(index, 1);
        that.setData({
            [in_count]: that.data.photo_count + 1,
            [in_source]: images,
        });
        that.data.image_src[in_source].splice(index, 1)
        console.log(that.data.other_files)
    },
    //婚姻状况选择
    marriageChange(e) {
        let value = e.detail.value
        this.setData({
            marriage: value,
            marriage_files: [], //结婚证
            divorce_files: [], //离婚证
            divorce_agree: [], //离婚协议
        })
    },
    //提交
    to_submit: function (e) {
        var that = this;
        // let client_list = that.data.client_list; //委托人信息
        // let marriage = that.data.marriage; //婚姻状态
        // let marriage_files = that.data.marriage_files; //结婚证
        // let divorce = that.data.divorce; //离婚证
        // let divorce_files = that.data.divorce_files; //离婚协议
        // let deed_files = that.data.deed_files; //房产证
        // let buy_files = that.data.buy_files; //购房协议
        // let inquire_files = that.data.inquire_files; //房产信息查询（产调）
        // let trustee_list = that.data.trustee_list; //受托人资料 （可多人）
        // let other_files = that.data.other_files; //其他
        // console.log(client_list.length)

        // pick_a 公证类型
        let number_goods = that.data.number_goods; //公证书份数
        let client_list = that.data.client_list; //委托人信息
        let client_marital_status = that.data.marriage; //婚姻状态
        if(client_marital_status>0){
            client_marital_status = client_marital_status -1;
        }
        // client_marital_status = client_marital_status == '2' ? '1': client_marital_status == '3' ? '2':0;
        let client_marriage_certificate = that.data.image_src.marriage_files; //结婚证
        // let client_divorce_certificate = that.data.image_src.divorce; //离婚证
        let client_divorce_agreement = that.data.image_src.divorce_files; //离婚协议
        let client_property_ownership_certificate = that.data.image_src.deed_files;//房产证
        let client_house_purchase_agreement = that.data.image_src.buy_files; //购房协议
        let client_property_information = that.data.image_src.inquire_files; //房产信息查询（产调）
        let trustee_list = that.data.trustee_list; //受托人资料 （可多人）
        let other = that.data.image_src.other_files; //其他
        if(typeof (client_divorce_agreement) == 'undefined'){
            client_divorce_agreement = '';
        }
        // if(typeof (client_divorce_certificate) == 'undefined'){
        //     client_divorce_certificate = '';
        // }
        if(typeof (client_house_purchase_agreement) == 'undefined'){
            client_house_purchase_agreement = '';
        }
        if(typeof (client_marriage_certificate) == 'undefined'){
            client_marriage_certificate = '';
        }
        if(typeof (client_property_information) == 'undefined'){
            client_property_information = '';
        }
        if(typeof (client_property_ownership_certificate) == 'undefined'){
            client_property_ownership_certificate = '';
        }
        if(typeof (other) == 'undefined'){
            other = '';
        }

        let base_type = 0; //委托类型
        // let client_number = 1; //委托人数
        let matter_id = that.data.matter_id;  //公证类型 or 1本人办理 2代理人办理
        let notarial_office_id = wx.getStorageSync('notarial_office_id');; //公证处
        let id = that.data.id




        // if (matter_id <= 0) {
        //     wx.showToast({
        //         title: '请选择公证类型',
        //         icon: 'none',
        //         mask: false,
        //     });
        //     return false;
        // }
        if (client_list.length <= 0) {
            wx.showToast({
                title: '请添加委托人',
                icon: 'none',
                mask: false,
            });
            return false;
        }
        this.setData({
            disabled: true
        })


        // wx.showModal({
        //     title: '弹出支付',
        //     content: '模拟支付',
        //     confirmText: '支付成功',
        //     cancelText: '支付失败',
        //     success(res) {
        //         if (res.confirm) {
        //             console.log('用户点击确定')
        //             wx.showToast({
                        // title: '上传中...',
                        // icon: 'loading',
                        // mask: true,
                        // duration: 1500,
                        // success(res) {

                            console.log(client_list);
                            let params = {}
                            //委托人信息 (多个)
                            params.client_list = JSON.stringify(client_list);
                            //         params.client_name =client_name;
                            //         params.client_phone =client_phone;
                            //         params.client_front_of_id_card =client_front_of_id_card;
                            //         params.client_reverse_side_of_id_card =client_reverse_side_of_id_card;
                            //         params.client_household_register =client_household_register;
                            // 关系证明
                            // params.proof_of_relationship =proof_of_relationship;
                            //婚姻状态
                            params.client_marital_status =client_marital_status;
                            //结婚证
                            params.client_marriage_certificate =client_marriage_certificate;
                            //离婚证
                            // params.client_divorce_certificate =client_divorce_certificate;
                            
                            //离婚协议
                            params.client_divorce_certificate =client_divorce_agreement;
                            // 房产证
                            params.client_property_ownership_certificate = client_property_ownership_certificate
                            // 购房协议
                            params.client_house_purchase_agreement = client_house_purchase_agreement
                            //房产信息查询（产调）
                            params.client_property_information = client_property_information
                            // 受托人资料 (多个)
                            params.trustee_list = JSON.stringify(trustee_list)

                            

                            // params.parents_household_register =parents_household_register;
                            params.other =other;

                            params.base_type =base_type;
                            params.client_number =client_list.length;
                            params.matter_id =matter_id;
                            params.notarial_office_id =notarial_office_id;
                            params.number_goods = number_goods;
                            // 大于0 修改 0 新增
                            params.id = id
                            console.log(params);
                            // JSON.stringify(info)
                            // return;
                            getApp()._post_form('data/api.auth.order/add', params, (result) => {
                                if (result.code==1) {
                                    let order_no = 0;
                                    setTimeout(() => { //上传成功后
                                        wx.redirectTo({
                                            url: '/pages/material/pages/pay_status/index?order_no='+order_no,
                                        })
                                    }, 1500)
                                    
                                }
                                else if(result.code==0)
                                {
                                            getApp().showError(result.info);
                                }
                                else{
                                    getApp().showError('传入正确的证件照或网络请求出错');
                                }
                                that.setData({
                                    disabled: false
                                })
                            })

                        // }
                //     });
                // } else if (res.cancel) {
                //     console.log('用户点击取消')
                //     this.setData({
                //         disabled: false
                //     })
                // }
            // }
        // })


    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // console.log(options);
        this.gettype();
        var id = options.id
        this.getInformation(id);
        // 获取公证类型
        // 购买数量
        if(typeof(options.number_goods) != 'undefined'){
            wx.setStorageSync('number_goods',options.number_goods)
        }
        this.setData({
            number_goods: wx.getStorageSync('number_goods'),
        });
    },
    //获取信息资料
    getInformation:function(id){
        console.log(id);
        let that = this
        let params = {}
        params.id = id;
        if(id > 0){
            this.setData({
                id: id,
            })
        }else{
            return;
        }
        getApp()._post_form('data/api.auth.order/getInformation', params, (result) => {
            let rt_data = result.data


            // let client_marriage_certificate = that.data.image_src.marriage_files; //结婚证
            // let client_divorce_certificate = that.data.image_src.divorce; //离婚证
            // let client_divorce_agreement = that.data.image_src.divorce_files; //离婚协议

            // let client_property_ownership_certificate = that.data.image_src.deed_files;//房产证
            // let client_house_purchase_agreement = that.data.image_src.buy_files; //购房协议
            // let client_property_information = that.data.image_src.inquire_files; //房产信息查询（产调）
            // let trustee_list = that.data.trustee_list; //受托人资料 （可多人）
            // let other = that.data.image_src.other_files; //其他
            
            let pick_a_name = 0;
            for (const key in that.data.picker_a) {
                if( that.data.picker_a[key]['id'] == rt_data.matter_id){
                    pick_a_name = key
                }

            }
            
            that.data.image_src = {
                marriage_files:rt_data.client_marriage_certificate,
                // divorce:rt_data.client_divorce_certificate,
                divorce_files:rt_data.client_divorce_certificate,
                // divorce_files:rt_data.client_divorce_agreement,
                deed_files:rt_data.client_property_ownership_certificate,
                buy_files:rt_data.client_house_purchase_agreement,
                inquire_files:rt_data.client_property_information,
            }

            this.setData({
                // 委托人信息
                client_list: rt_data.client_json,
                no_list :false,
                // 婚姻状态
                marriage: rt_data.client_marital_status,
                // 结婚证
                marriage_files:rt_data.client_marriage_certificate,
                // 离婚证
                // divorce:rt_data.client_divorce_certificate,
                // 离婚协议
                divorce_files:rt_data.client_divorce_certificate,
                // 房产证
                deed_files:rt_data.client_property_ownership_certificate,
                // 购房协议
                buy_files:rt_data.client_house_purchase_agreement,
                // 房产信息查询（产调）
                inquire_files:rt_data.client_property_information,
                // 受托人资料
                trustee_list:rt_data.trustee_id_card,
                trustee_no: false,

                other_files:rt_data.other,
                base_type:0,
                matter_id:rt_data.matter_id,

                pick_a:pick_a_name,
                notarial_office_id:rt_data.notarial_office_id,
                disabled: rt_data.status == 2 ? false:true,
                update_disabled:rt_data.status == 2 ? true:false,
            });
        })
    },
    gettype:function(){
        let notarial_office_id = wx.getStorageSync('notarial_office_id'); //公证处
        let params = {notarial_office_id:notarial_office_id}
        getApp()._post_form('data/api.auth.order/gettype', params, (result) => {
            this.setData({
                picker_a: result.data,
            });
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },
    

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },
    

    
      
})
